
package com.putao.album.album;

import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.putao.album.R;
import com.putao.album.album.bean.GalleryEntity;
import com.putao.album.album.bean.PhotoGridItem;
import com.putao.album.album.util.PhotoSelectUtil;
import com.putao.album.base.BaseActivity;
import com.putao.album.child.crop.ActivityCropImage;
import com.putao.album.dialog.ConfirmDialogBuilder;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.fileupload.FileInfo;
import com.putao.album.fileupload.FileUploadDBHelper;
import com.putao.album.fileupload.FileUploadManager;
import com.putao.album.main.AlbumHomeActivity;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.FastBlur;
import com.putao.album.util.NetUtil;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.UmengTouchEvent;
import com.putao.album.widget.stickygridheaders.StickyGridHeadersGridView;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class ActivityAlbumPhotoSelect extends BaseActivity implements View.OnClickListener, AlbumGridAdapter.UpdateCallback {
    private Button back_btn, right_btn;
    private ListView layout_gallery_list;
    private final static int SetAlbumPhotos = 1;
    private final static int SetGalleryList = 2;
    private final static int reloadNewData = 3;
    private StickyGridHeadersGridView mGridView;
    private List<PhotoGridItem> mGirdList = new ArrayList<PhotoGridItem>();
    private LinearLayout sl_gallery_list;
    private boolean mGalleryShow = false;
    ArrayList<GalleryEntity> mGalleryList;
    private RelativeLayout gallery_list_panel;
    private TextView title_tv;
    private boolean multiSelectState = true;
    public static final int MAX_SELECTED = 100;
    public static final String IS_CAMERA_ICON = "isCameraIcon";
    private static final int REQUEST_CODE = 1;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case SetAlbumPhotos:
                    LoadAlbumData();
                    break;
                case SetGalleryList:
                    loadGalleryList();
                    break;
                case reloadNewData:
                    reSetAlbumData();
                    break;
                default:
                    break;
            }
        }
    };
    private AlbumGridAdapter mAlbumGridAdapter;
    private LinearLayout nonePhotoView;
    private RelativeLayout grid_rl;
    private ImageView body_iv_none_camera;
    private LinearLayout upload_ll;
    private Button upload_btn;
    private boolean isRegister;
    private int bucket_id = -1;
    private ArrayList<String> photoTakes = new ArrayList<String>();

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_album_photo_select;
    }

    Uri mPhotoUri;

    private void startCameraApp() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            ContentValues contentValues = new ContentValues(2);
            contentValues.put(MediaStore.Images.Media.DATA, CommonUtils.getOutputMediaFile().getPath());
            contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            mPhotoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
            startActivityForResult(intent, REQUEST_CODE);
        }
        MobclickAgent.onEvent(mContext, UmengTouchEvent.CLICK_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            Uri uri = null;
            if (data != null && data.getData() != null) {
                uri = data.getData();
            }
            if (uri == null) {
                if (mPhotoUri != null) {
                    uri = mPhotoUri;
                }
            }
            try {
                String[] projection = {MediaStore.MediaColumns._ID, MediaStore.Images.ImageColumns.ORIENTATION, MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(uri, projection, null, null, null);
                c.moveToFirst();
                String photoFileName = c.getString(c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                File file = new File(photoFileName);
                File destDir = CommonUtils.getOutputMediaDir();
                file.renameTo(destDir);
                String photo_path = destDir.getPath() + File.separator + file.getName();
                final String[] SCAN_TYPES = {"image/jpeg"};

                String time = new SimpleDateFormat("yyyy-MM-dd HHmmss").format(new Date(new File(photo_path).lastModified()));
                //Loger.d("chen+++++oiaScannerConnection.scanFile:"+photo_path);
                MediaScannerConnection.scanFile(mContext, new String[]{photo_path}, SCAN_TYPES, new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                        //Loger.d("chen+++++onScanCompleted:"+path);
                        photoTakes.add(path);
                        sendHandleMessage(reloadNewData);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            getContentResolver().delete(mPhotoUri, null, null);
        }
    }

    @Override
    public void doInitSubViews(View view) {
        nonePhotoView = (LinearLayout) this.findViewById(R.id.body_iv_none);
        body_iv_none_camera = (ImageView) this.findViewById(R.id.body_iv_none_camera);
        body_iv_none_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //                Bundle bundle = new Bundle();
                //                bundle.putString("reason", "edit");
                //                 ActivityHelper.startActivity(mActivity, MovieCameraActivity.class, bundle);
                startCameraApp();
            }
        });
        mGridView = (StickyGridHeadersGridView) findViewById(R.id.asset_grid);
        back_btn = (Button) this.findViewById(R.id.back_btn);
        title_tv = (TextView) this.findViewById(R.id.title_tv);
        title_tv.setText(getString(R.string.photo_select_title));
        right_btn = (Button) findViewById(R.id.right_btn);
        right_btn.setBackgroundColor(getResources().getColor(R.color.transparent));
        right_btn.setText(getString(R.string.photo_select_others));
        right_btn.setTextColor(getResources().getColor(R.color.blue));
        upload_ll = (LinearLayout) this.findViewById(R.id.upload_ll);
        upload_btn = (Button) this.findViewById(R.id.upload_btn);
        grid_rl = (RelativeLayout) findViewById(R.id.grid_rl);
        layout_gallery_list = (ListView) findViewById(R.id.layout_gallery_list);
        sl_gallery_list = (LinearLayout) findViewById(R.id.sl_gallery_list);
        gallery_list_panel = (RelativeLayout) findViewById(R.id.gallery_list_panel);
        gallery_list_panel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mGalleryShow) {
                    hideGalleryLsit();
                }
            }
        });
        gallery_list_panel.setVisibility(View.GONE);
        addOnClickListener(back_btn, right_btn, upload_btn);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String path = mGirdList.get(position).getPath();
                if (IS_CAMERA_ICON.equals(path)) {
                    startCameraApp();
                } else if (!isMultiSelectState()) {
                    Bundle bundle = new Bundle();
                    bundle.putString("photo_path", path);
                    ActivityHelper.startActivity(mActivity, ActivityCropImage.class, bundle);
                    finish();
                } else if (isMultiSelectState()) {
                    if (FileUploadDBHelper.getInstance().isUploadSuccess(CommonUtils.getBabyId(), path)) {
                        return;
                    }

                    PhotoGridItem item = mGirdList.get(position);
                    if (item.isSelected()) {
                        item.setSelected(false);
                    } else {
                        if (getSelectNum() >= MAX_SELECTED) {
                            showToast(getString(R.string.select_all_to_max));
                        } else {
                            item.setSelected(true);
                        }
                    }
                    mAlbumGridAdapter.notifyDataSetChanged();
                    updateTextView();
                }
            }
        });
        mGridView.setHeadersIgnorePadding(true);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void doInitData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            boolean State = bundle.getBoolean("multiSelectState", true);
            isRegister = bundle.getBoolean("isRegister", false);
            setMultiSelectState(State);
            if (!isMultiSelectState()) {
                upload_ll.setVisibility(View.GONE);
            }
        }
        //getData();
        getGallery();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    void getGallery() {
        final ProgressDialog dialog = new ProgressDialog(mContext);
        dialog.setMessage("正在读取照片...");
        dialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                mGalleryList = PhotoSelectUtil.QueryALLGalleryList(mContext);

                sendHandleMessage(SetGalleryList);

                for (int i = 0; i < mGalleryList.size(); i++) {
                    GalleryEntity item = mGalleryList.get(i);
                    if (item.getImage_path().contains(PuTaoConstants.SYSTEM_CAMERA_FOLDER)) {
                        bucket_id = item.getBucket_id();
                    }
                }
                dialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        reSetAlbumData();
                    }
                });
            }
        }).start();
    }

    private void addCameraItem() {
        if (mGirdList.size() > 0) {
            if (mGirdList.get(0).getPath().toUpperCase().contains(PuTaoConstants.SYSTEM_CAMERA_FOLDER)) {
                String curdate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
                PhotoGridItem item = new PhotoGridItem(IS_CAMERA_ICON, curdate, null, 0);
                if(curdate.equals(mGirdList.get(0).getTime())) {
                    //在当前日前组的最前面
                    item.setSection(1);
                }else{
                    //在当前日前,单独一组
                    item.setSection(0);
                }
                mGirdList.add(0, item);
            }
        }
    }

    void reSetAlbumData() {
        final ProgressDialog dialog = new ProgressDialog(mContext);

        dialog.setMessage("正在更新相册照片...");

        dialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (bucket_id != -1) {
                    mGirdList = PhotoSelectUtil.QueryPhotoByBUCKET_ID(mContext, bucket_id);
                } else {
                    mGirdList = PhotoSelectUtil.QueryALLPhoto(mContext);
                }
                addCameraItem();
                if (isMultiSelectState()) {
                    for (int i = 0; i < mGirdList.size(); i++) {
                        PhotoGridItem item = mGirdList.get(i);
                        //Loger.d("chen+++++item.getPath():"+item.getPath());
                        for (int j = 0; j < photoTakes.size(); j++) {
                            if (photoTakes.get(j).equals(item.getPath())) {
                                item.setSelected(true);
                            }
                        }
                    }
                }
                sendHandleMessage(SetAlbumPhotos);
                dialog.dismiss();
            }
        }).start();
    }

    void loadGalleryList() {
        GalleryListAdapter galleryAdapter = new GalleryListAdapter(mContext, mGalleryList);
        layout_gallery_list.setAdapter(galleryAdapter);
        layout_gallery_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MobclickAgent.onEvent(mContext, UmengTouchEvent.SELECT_OTHERALBUM);
                GalleryEntity entity = mGalleryList.get(position);
                bucket_id = entity.getBucket_id();
                reSetAlbumData();
                String name = entity.getBucket_name();
                if (entity.getImage_path().toUpperCase().contains(PuTaoConstants.SYSTEM_CAMERA_FOLDER)) {
                    name = getString(R.string.photo_select_title);
                }
                title_tv.setText(name);
                hideGalleryLsit();
            }
        });
    }

    void LoadAlbumData() {
        mAlbumGridAdapter = new AlbumGridAdapter(mActivity, mGirdList, mGridView, this);
        mGridView.setAdapter(mAlbumGridAdapter);
        mAlbumGridAdapter.setMultiSelect(isMultiSelectState());
        if (mGirdList.size() > 0 && (!IS_CAMERA_ICON.equals(mGalleryList.get(0).getImage_path()))) {
            nonePhotoView.setVisibility(View.INVISIBLE);
            mGridView.setVisibility(View.VISIBLE);
        } else {
            nonePhotoView.setVisibility(View.VISIBLE);
            mGridView.setVisibility(View.INVISIBLE);
        }
        updateTextView();
    }

    void getData() {
        final ProgressDialog dialog = new ProgressDialog(mContext);
        dialog.setMessage("正在读取照片...");
        //部分手机,如Lenovo,此时显示Dialog会有异常:无Window
        //dialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                mGirdList = PhotoSelectUtil.QueryALLPhoto(mContext);
                addCameraItem();
                sendHandleMessage(SetAlbumPhotos);
                dialog.dismiss();
            }
        }).start();
    }

    private void sendHandleMessage(int messagecode) {
        Message msg = new Message();
        msg.what = messagecode;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                if (isRegister) {
                    ActivityHelper.startActivity(mActivity, AlbumHomeActivity.class);
                }
                finish();
                break;
            case R.id.right_btn:
                if (mGalleryShow) {
                    hideGalleryLsit();
                } else {
                    showGalleryList();
                }
                break;
            case R.id.upload_btn:
                uploadBtnOnClick();
                break;
            default:
                break;
        }
    }

    private void blur(Bitmap bkg, View view) {
        long startMs = System.currentTimeMillis();
        float scaleFactor = 32;
        float radius = 4;
        Bitmap overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth() / scaleFactor), (int) (view.getMeasuredHeight() / scaleFactor),
                Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(overlay);
        canvas.translate(-view.getLeft() / scaleFactor, -view.getTop() / scaleFactor);
        canvas.scale(1 / scaleFactor, 1 / scaleFactor);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(bkg, 0, 0, paint);
        canvas.drawColor(0x99ffffff);
        overlay = FastBlur.doBlur(overlay, (int) radius, true);
        // view.setBackground(new BitmapDrawable(getResources(), overlay));
        view.setBackgroundDrawable(new BitmapDrawable(getResources(), overlay));
        //        Loger.d("blur()++++++time=" + (System.currentTimeMillis() - startMs) + "ms");
    }

    private void applyBlur() {
        grid_rl.setDrawingCacheEnabled(true);
        grid_rl.buildDrawingCache();
        final Bitmap bmp = grid_rl.getDrawingCache();
        sl_gallery_list.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                sl_gallery_list.getViewTreeObserver().removeOnPreDrawListener(this);
                blur(bmp, sl_gallery_list);
                grid_rl.setDrawingCacheEnabled(false);
                return true;
            }
        });
    }

    void showGalleryList() {
        applyBlur();
        gallery_list_panel.setBackgroundColor(0x66000000);
        ObjectAnimator.ofFloat(sl_gallery_list, "translationX", 0, sl_gallery_list.getWidth()).setDuration(10).start();
        sl_gallery_list.setVisibility(View.VISIBLE);
        gallery_list_panel.setVisibility(View.VISIBLE);
        ObjectAnimator.ofFloat(sl_gallery_list, "translationX", sl_gallery_list.getWidth(), 0).setDuration(300).start();
        mGalleryShow = true;
    }

    void hideGalleryLsit() {
        gallery_list_panel.setBackgroundColor(0x00000000);
        ObjectAnimator.ofFloat(sl_gallery_list, "translationX", 0, sl_gallery_list.getWidth()).setDuration(300).start();
        mGalleryShow = false;
        gallery_list_panel.postDelayed(new Runnable() {
            @Override
            public void run() {
                gallery_list_panel.setVisibility(View.GONE);
            }
        }, 550);
    }

    public boolean isMultiSelectState() {
        return multiSelectState;
    }

    public void setMultiSelectState(boolean multiSelectState) {
        this.multiSelectState = multiSelectState;
    }

    private void uploadBtnOnClick(){
        if (getSelectNum() <= 0) {
            showToast("请选择选择照片");
            return;
        }
        if(!NetUtil.isWifiEnable(mContext)&&CommonUtils.isOnlyWifiUploadOpen()){

            new ConfirmDialogBuilder(mContext)
                    .setMessage("当前WIFI不可用,继续\n上传会产生流量!")
                    .setPositiveButton("继续上传", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            uploadSelectedAlbumPhotos(true);
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("等待WIFI", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            uploadSelectedAlbumPhotos(false);
                            dialog.dismiss();
                        }
                    })
                    .Create()
                    .show();
            return;
        }

        uploadSelectedAlbumPhotos(false);
    }

    private void uploadSelectedAlbumPhotos(boolean forceNoWifiUpload) {
        LinkedList<FileInfo> mFilelist = new LinkedList<FileInfo>();
        String babyId = CommonUtils.getBabyId();
        for (int i = 0; i < mGirdList.size(); i++) {
            PhotoGridItem item = mGirdList.get(i);
            if (item.isSelected()) {
                String filePath = item.getPath();
                FileInfo info = new FileInfo(filePath, null, null);
                info.setBabyId(babyId);
                mFilelist.add(info);
            }
        }

        FileUploadManager pm = FileUploadManager.getIntance();
        pm.setFiles(mFilelist);
        pm.setForceNoWifiUpload(forceNoWifiUpload);
        pm.start();

        if (isRegister) {
            //注册完-->添加宝宝-->添加宝宝完-->上传照片(此时还未进入AlbumHomeActivity)
            ActivityHelper.startActivity(mActivity, AlbumHomeActivity.class);
        }
        Bundle bundle = new Bundle();
        bundle.putSerializable("local_photo", mFilelist);
        EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_UPLOAD_LOCAL_PHOTOS, bundle));
        mActivity.finish();
    }

    public void onEvent(BasePostEvent event) {
        switch (event.eventCode) {
            case PuTaoConstants.FINISH_TO_MENU_PAGE:
                finish();
                break;
        }
    }

    @Override
    public void updateTextView() {
        String upload_btn_tx;
        int select_num = getSelectNum();
        if (select_num > 0)
            upload_btn_tx = getString(R.string.upload) + "  " + select_num + "/" + MAX_SELECTED;
        else
            upload_btn_tx = getString(R.string.please_select_photo);
        upload_btn.setText(upload_btn_tx);
    }

    @Override
    public int getSelectNum() {
        int total = 0;
        for (int i = 0; i < mGirdList.size(); i++) {
            if (mGirdList.get(i).isSelected()) {
                total++;
            }
        }
        return total;
    }
}
